package com.sec.etech.org.service;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sec.etech.org.dao.*;
import com.sec.etech.org.dto.OrgUserSyncHrsExtend;
import com.sec.etech.org.model.OrgGroup;
import com.sec.etech.org.model.OrgGroupSyncHrs;
import com.sec.etech.org.model.OrgRelation;
import com.sec.etech.org.model.OrgUser;
import com.sec.etech.org.repository.OrgUserSyncHrsRepository;
import com.sec.etech.sys.util.ContextUtil;
import com.sec.etech.sys.util.DbUtil;
import com.sec.etech.sys.util.PropertyUtil;
import org.openbpm.base.api.response.impl.ResultMsg;
import org.openbpm.base.core.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class OrgUserSyncHrsService {
    @Autowired
    private OrgUserSyncHrsRepository orgUserSyncHrsRepository;
    @Autowired
    private OrgUserSyncHrsExtendMapper orgUserSyncHrsExtendMapper;
    @Autowired
    private OrgUserMapper orgUserMapper;
    @Autowired
    private OrgRelationMapper orgRelationMapper;
    @Autowired
    private OrgGroupSyncHrsMapper orgGroupSyncHrsMapper;
    @Autowired
    private OrgGroupMapper orgGroupMapper;
    @Autowired
    private EtechGroupService etechGroupService;

    //转换器，把hrs的数据转到orgUser
    public OrgUser orgUserSyncHrsExtentConvert(OrgUserSyncHrsExtend orgUserSyncHrsExtend) {
        OrgUser orgUser = new OrgUser();
        orgUser.setId(orgUserSyncHrsExtend.getEtechUserId());
        orgUser.setFullname(orgUserSyncHrsExtend.getFullname());
        orgUser.setAccount(orgUserSyncHrsExtend.getAccount());
        orgUser.setEmail(orgUserSyncHrsExtend.getEmail());
        orgUser.setSex(orgUserSyncHrsExtend.getSex());
        orgUser.setStatus(orgUserSyncHrsExtend.getStatus());
        orgUser.setCreateTime(orgUserSyncHrsExtend.getCreateTime());
        orgUser.setCreateBy(orgUserSyncHrsExtend.getCreateByUserId());
        orgUser.setUpdateTime(orgUserSyncHrsExtend.getUpdateTime());
        orgUser.setUpdateBy(orgUserSyncHrsExtend.getUpdateByUserId());
        //拼接并去重备注
        List<String> remarkList = new ArrayList<>();
        if (orgUserSyncHrsExtend.getEtechRemark() != null) {
            String[] EtechRemarkList = orgUserSyncHrsExtend.getEtechRemark().split(";");
            for (String EtechRemark : EtechRemarkList) {
                if (!remarkList.contains(EtechRemark)) {
                    remarkList.add(EtechRemark);
                }
            }

        }
        if (!remarkList.contains(orgUserSyncHrsExtend.getRemark())) {
            remarkList.add(orgUserSyncHrsExtend.getRemark());
        }
        orgUser.setRemark(ContextUtil.concat(remarkList, ";"));

        orgUser.setPassword(orgUserSyncHrsExtend.getEtechPassword() == null ?
                orgUserSyncHrsExtend.getPassword() : orgUserSyncHrsExtend.getEtechPassword());
        return orgUser;
    }



    //转换器，把hrs的数据转换到org_group
    public OrgGroup orgGroupSyncHrsConvert(OrgGroupSyncHrs orgGroupSyncHrs) {
        //取出数据
        OrgGroup orgGroup = new OrgGroup();
        OrgGroup parentGroup = orgGroupMapper.selectOne(new QueryWrapper<OrgGroup>().eq("code_", orgGroupSyncHrs.getParentId()));
        OrgGroup etechGroup = orgGroupMapper.selectOne(new QueryWrapper<OrgGroup>().eq("code_", orgGroupSyncHrs.getId()));
        OrgUser createBy = orgUserMapper.selectOne(new QueryWrapper<OrgUser>().eq("account_", orgGroupSyncHrs.getCreateBy()));
        OrgUser updateBy = orgUserMapper.selectOne(new QueryWrapper<OrgUser>().eq("account_", orgGroupSyncHrs.getUpdateBy()));

        orgGroup.setId(etechGroup == null ? null : etechGroup.getId());
        orgGroup.setParentId(parentGroup == null ? null : parentGroup.getId());
        orgGroup.setCreateBy(createBy == null ? null : createBy.getId());
        orgGroup.setUpdateBy(updateBy == null ? null : updateBy.getId());

        orgGroup.setName(orgGroupSyncHrs.getName());
        orgGroup.setSn(100L);
        orgGroup.setCode(orgGroupSyncHrs.getId());
        orgGroup.setType(orgGroupSyncHrs.getType());
        orgGroup.setDesc(orgGroupSyncHrs.getDesc());
        orgGroup.setCreateTime(orgGroupSyncHrs.getCreateTime());
        orgGroup.setUpdateTime(orgGroupSyncHrs.getUpdateTime());
        orgGroup.setOrderby(orgGroupSyncHrs.getOrderby());
        orgGroup.setLevel(orgGroupSyncHrs.getLevel());
        orgGroup.setIsLeaf(orgGroupSyncHrs.getIsLeaf());
        orgGroup.setActive(orgGroupSyncHrs.getActive());
        return orgGroup;
    }

    //更新用户部门关系表
    @Transactional
    public void insertOrgRelation(OrgUserSyncHrsExtend orgUserSyncHrsExtend, String userId) {
        //先删除
        orgRelationMapper.delete(
                new QueryWrapper<OrgRelation>()
                        .eq("user_id_", userId)
                        .eq("type_", "groupUser")
                        .eq("status_", "1"));
        //再新增
        OrgRelation orgRelation = new OrgRelation();
        orgRelation.setGroupId(orgUserSyncHrsExtend.getEtechGroupId());
        orgRelation.setUserId(userId);
        orgRelation.setIsMaster(1L);
        if(orgUserSyncHrsExtend.getStatus()==0){
            //修改其部门为无部门
            orgRelation.setGroupId("9999");
            //删除禁用状态用户的角色
            String sql="select id_ from org_relation where role_id_ is not null and user_id_ = ?";
            List<Map<String, Object>> maps = DbUtil.getJdbcTemplate().queryForList(sql, orgRelation.getUserId());
            if (maps.size()>=1){
                for (Map<String, Object> map : maps) {
                    String sql2="delete from org_relation where id_=?";
                    DbUtil.getJdbcTemplate().update(sql2,map.get("id_"));
                }
            }
        }
        orgRelation.setStatus(orgUserSyncHrsExtend.getStatus());
        orgRelation.setType("groupUser");
        orgRelation.setCreateTime(orgUserSyncHrsExtend.getCreateTime());
        orgRelation.setUpdateTime(orgUserSyncHrsExtend.getUpdateTime());
        orgRelation.setCreateBy(orgUserSyncHrsExtend.getCreateByUserId());
        orgRelation.setUpdateBy(orgUserSyncHrsExtend.getUpdateByUserId());
        orgRelationMapper.insert(orgRelation);
    }

    //从同步表中插入组织
    @Transactional
    public void syncOrgGroup() {
        //先插入
        List<OrgGroupSyncHrs> orgGroupSyncHrsInsertList = orgGroupSyncHrsMapper.getOrgGroupSyncHrsInsertList();
        for (OrgGroupSyncHrs orgGroupSyncHrs : orgGroupSyncHrsInsertList) {
            orgGroupMapper.insert(orgGroupSyncHrsConvert(orgGroupSyncHrs));
        }

        //再修改
        List<OrgGroupSyncHrs> orgGroupSyncHrsUpdateList = orgGroupSyncHrsMapper.getOrgGroupSyncHrsUpdateList();
        for (OrgGroupSyncHrs orgGroupSyncHrs : orgGroupSyncHrsUpdateList) {
            orgGroupMapper.updateById(orgGroupSyncHrsConvert(orgGroupSyncHrs));
        }

        //更新全程表
        etechGroupService.refreshGroupView();
    }

    //删除数据
    @Transactional
    public ResultMsg<Boolean> del(JSONArray jsonArray) {
        return new ResultMsg<>(orgUserSyncHrsRepository.del(jsonArray));
    }

    //同步数据,对于正式服只做增改人的操作，并将人员同步到测试。随后到测试服一条龙，再同步到正式
    @Transactional
    public ResultMsg<Boolean> sync() {
        Boolean isProd = PropertyUtil.getPropertyService().getByAlias("systemEnvironmentVariables").equals("prod");

        String sql = "select account_ from org_user_sync_whitelist";
        List<Map<String, Object>> list = DbUtil.getJdbcTemplate().queryForList(sql);
        List<OrgUserSyncHrsExtend> orgUserSyncHrsExtendList = orgUserSyncHrsExtendMapper.getOrgUserSyncHrsExtentList();
        Boolean flag = false;
        for (OrgUserSyncHrsExtend orgUserSyncHrsExtend : orgUserSyncHrsExtendList) {
            //先判断非空，非生产服
            if (isProd || orgUserSyncHrsExtend.getUpdateRemark() == null) {
                continue;
            }
            String account = orgUserSyncHrsExtend.getAccount();

            for (Map<String, Object> map : list) {
                if (!StringUtil.isEmpty((String) map.get("account_")) && map.get("account_").equals(account)) {
                    flag = true;
                }
            }
            if (flag) {
                flag = false;
                continue;
            }
            //新增和修改人员及属性
            if (orgUserSyncHrsExtend.getUpdateRemark().contains("account_") && StringUtil.isEmpty(orgUserSyncHrsExtend.getEtechUserId())) {
                OrgUser orgUser = orgUserSyncHrsExtentConvert(orgUserSyncHrsExtend);
                orgUserMapper.insert(orgUser);
                insertOrgRelation(orgUserSyncHrsExtend, orgUser.getId());
            }
            //更新人员数据
            else if (orgUserSyncHrsExtend.getUpdateRemark().length() > 0) {
                OrgUser orgUser = orgUserSyncHrsExtentConvert(orgUserSyncHrsExtend);
                orgUserMapper.updateById(orgUser);
                if (orgUserSyncHrsExtend.getStatus() == 0) {
                    insertOrgRelation(orgUserSyncHrsExtend, orgUser.getId());
                }
            }

            //修改人员部门
            if (orgUserSyncHrsExtend.getUpdateRemark().contains("group_id")) {

                //再新增
                insertOrgRelation(orgUserSyncHrsExtend, orgUserSyncHrsExtend.getEtechUserId());
            }
        }
        return new ResultMsg<>(true);
    }

    //对比数据
    public ResultMsg<Boolean> diff() {
        //先同步组织架构
        syncOrgGroup();
        //
        etechGroupService.repair();
        Boolean success = orgUserSyncHrsRepository.diff();
        return new ResultMsg<>(success);
    }
}
